<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>物资列表</title>
    <link rel="stylesheet" href="/css/elementui/index.css">
    <link rel="stylesheet" href="/css/exam/css/style.css">
    <link rel="stylesheet" href="/iconfont/iconfont.css">
    <script src="/css/exam/js/httpVueLoader.js"></script>
</head>
<body>
<div id="app">
  <!--导航切换-->

  <div class="p-30">
    <el-row type="flex" class="row-bg" justify="space-between">
	
       <el-form :inline="true" :model="formInline" ref="formInline" label-width="100px" class="demo-ruleForm">
           <el-form-item label="">
                <el-input v-model="formInline.name" placeholder="请选择物资名称"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchput('formInline')">搜&ensp;&ensp;索</el-button>
                <el-button @click="resetForm('formInline')">重&ensp;&ensp;置</el-button>
            </el-form-item>
        </el-form>
      <el-row>
	  <el-button type="primary" @click="handleEdit"><span style="display:block;color:#fff;text-decoration:none">新&ensp;&ensp;增</a></el-button>
        <el-button type="primary" @click="downloadExcel()"><span style="display:block;color:#fff;text-decoration:none"><i class="el-icon-download"></i>导&ensp;&ensp;出</a></el-button>
      </el-row>
    </el-row>

    <template>
        <el-table  :data="list"  border  style="width: 100%" v-loading="loading">   
            <el-table-column prop="id"  label="序&ensp;&ensp;号"  width="80"> </el-table-column>
            <el-table-column prop="name" label="物资名称" width=""> </el-table-column>
            <el-table-column prop="goods.name" label="物资分类" width=""> </el-table-column>
            <el-table-column prop="attribute" label="物资属性" width="" v-if="false"> </el-table-column>
            <el-table-column fixed="right"  label="操&ensp;&ensp;作"  width="">
            <template slot-scope="scope">
			    <el-button size="mini"  type="primary"><a  style="color:#fff" :href="'/admin/warehouse/materialdetail?id=' + scope.row.id">详&ensp;&ensp;情</a></el-button>
                <el-button size="mini"  type="primary" @click="handleEdit(scope.$index, scope.row)"> 修&ensp;&ensp;改 </el-button>
                <el-button  @click.native.prevent="deleteRow(scope.$index, scope.row)"    size="mini"  type="danger" >删&ensp;&ensp;除</el-button>
                      
            </template>
            </el-table-column>
        </el-table>
		<el-alert title="*（ 备注：只有入库、出库、在库、损耗数量均为0时才可删除分类 ）" type="error" style="background-color:transparent"></el-alert>
        <!-- 分页组件 -->
        <div class="block" style="margin-top:15px;">
            <el-pagination align='center' @size-change="handleSizeChange" @current-change="handleCurrentChange" 
            :current-page="currentPage" 
            :page-sizes="[15,30,50,100]" 
            :page-size="pageSize" 
            layout="total, sizes, prev, pager, next, jumper" 
            :total="count">
            </el-pagination>
        </div>
    </template>
	<!--修改物资名称-->
	  <el-dialog
	      :title="title"
	      :visible.sync="outerVisible"
	      width="50%"
	      :append-to-body="true"
	      >
	      <el-form :model="addmForm" :rules="rules" ref="addmForm" label-width="100px" class="demo-ruleForm">
			  <el-form-item label="物资分类" prop="goods_id_arr">
			       <el-cascader
			           class="w-400px"
			           :clearable="true"
			           :options="goodsdata"
			           :props="props"
			           v-model="addmForm.goods_id_arr"
			  		   placeholder="请选择分类名称"
			         	clearable
			  			ref='postSelectRef'
			  			@change='postValueChange($event)'
			       ></el-cascader>
			  </el-form-item>
			  <el-form-item  label="物资属性" prop="attribute">
				<el-radio-group v-model="addmForm.attribute">									
					<el-radio :label="1">消耗品</el-radio>
					<el-radio :label="2">固定资产</el-radio>
				</el-radio-group>
			  </el-form-item>
			  <el-form-item label="物资名称" prop="name">
				  <el-input v-model="addmForm.name"></el-input>
			  </el-form-item>
			  <el-form-item label="备&ensp;&ensp;注">
				  <el-input v-model="addmForm.remarks"></el-input>
			  </el-form-item>
			  <el-form-item label="图&ensp;&ensp;片">
				<el-upload
				  class="avatar-uploader"
				  action="/admin/upload/uploadimg?_token={{ csrf_token() }}"
				  :show-file-list="false"
				  :on-success="handleAvatarSuccess"
				  :before-upload="beforeAvatarUpload"
				  ref='upload'
				  >
				  <img v-if="addmForm.img_url" :src="addmForm.img_url" class="avatar">
				  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
				</el-upload>
			  </el-form-item> 
	      </el-form>
	      <span slot="footer" class="dialog-footer">
	      <el-button @click="resetAddForm('addmForm')">取&ensp;&ensp;消</el-button>
	      <el-button type="primary" @click="saveMaterial('addmForm')"  v-debounce>确&ensp;&ensp;定</el-button>
	      </span>
	  </el-dialog> 
       <!--添加物资分类-->
	   <!--
       <el-dialog
        title="添加物资分类"
        :visible.sync="innerVisible"
        :append-to-body="true"
        width="50%">
        <el-form :model="addgForm" :rules="rules" ref="addgForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="分类名称" prop="name">
		  <el-cascader
		      class="w-400px"
		      :clearable="true"
		      :options="industrys"
		      :props="props"
		      v-model="addgForm.name"
		  ></el-cascader>
          </el-form-item>
          <el-form-item label="备&ensp;&ensp;注">
            <el-input v-model="addgForm.remarks"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveGoods('addgForm')"  v-debounce>确&ensp;&ensp;定</el-button>
		  <el-button @click="innerVisible = false">取&ensp;&ensp;消</el-button>	  
		</span>
      </el-dialog> -->

  </div>

</div>

<script src="/css/exam/js/vue.js"></script>
<script src="/css/elementui/index.js"></script>
<script src="/css/exam/js/axios.min.js"></script>
<script src="/css/exam/js/common.js"></script>
<script>
var validCascader = (rule, value, callback) => {
  if (this.cascadeValue.length == 0) {
    callback(new Error('不能为空'))
  } else {
    callback();
  }
};
const app = new Vue({
  el: '#app',
  data() {
    return { 
      loading: false,
      list: [], //数据
      goodsdata:[],
      currentPage: 1, // 当前页码
      count: 10, // 总条数
      pageSize: 15,// 每页的数据条数
      formInline:{
        name:null,
      },

      addmForm:{
        id:'',
        goods_id:'',
		goods_id_arr:[],
        attribute:'',
        name:'',
        remarks:'',
		img_url:'',
      },

      addgForm:{
        name:'',
        remarks:'',

      },
      outerVisible: false,
      innerVisible: false,

      title:'',

      url:'',
      file_name:'',
	  props: {
	    value: 'id',
	    label: 'name',
	    children: 'children',
	    checkStrictly: true,
	  },
	  CascaderLabel:'',
      rules: {
          goods_id_arr: [
            { type: 'array', required: true, message: '请选择', trigger: 'blur'},
          ],
          name: [
            { required: true, message: '请输入', trigger: 'blur'},
          ],
          attribute: [
            { required: true}
          ],
        },
    }
  },
  created() {
    this.getdata(),
    this.getgoodsdata()
  },

  methods: {
         // 删除列表行
          deleteRow(index, rows) { 
                this.$confirm('确定要删除吗?', '信息', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                   
                })
                .then(() => {                  
                  axios.post('/admin/materialList/delete',{id:rows.id})
                    .then(response =>{						
                      this.getdata()   
					   if(response.data.code==200){
					   		this.$message.success("删除成功")
					   }
					  if(response.data.code==408){
						 this.$message.error(response.data.message)
					  }
                    }).catch(error =>{
												
                    })
                })
          },
          //获取物资列表
          getdata() {    
            this.loading = true  
            let vm = this 
            axios.post('/admin/materialList/list_data',{name:vm.formInline.name,page:vm.currentPage,limit:vm.pageSize})
            .then(response =>{
                vm.list = response.data.data.list;
                vm.count = response.data.data.count; 
                vm.loading = false; 
            }).catch(error =>{
                console.log('请求失败：' + error);
                vm.loading = false; 
            })
          }, 
            //获取物资分类
            getgoodsdata() {  
                let vm = this   
                axios.post('/admin/goods/goods_all')
                .then(response =>{
                    vm.goodsdata = response.data.data;
                }).catch(error =>{
                    console.log('请求失败：' + error);
                })
            }, 
          // 搜索事件         
          searchput(){
            this.currentPage = 1;
            this.getdata() 
          }, 
          resetForm(formName) {
			this.formInline.name = null
            this.getdata() 
          },
          // 分页页码  
          handleSizeChange(val){
            console.log(`每页 ${val} 条`);
			      this.currentPage = 1;
			      this.pageSize = val;
            this.getdata()
          },
          handleCurrentChange(val){
            console.log(`当前页: ${val}`);
			      this.currentPage = val;
            this.getdata()
					  
          },
         //显示编辑界面
          handleEdit(index, row) {
            this.outerVisible = true
            if (row != undefined && row != 'undefined') {
              this.title = '物资修改'
			  this.addmForm.img_url = ''
              this.addmForm.id = row.id
              this.addmForm.goods_id_arr = row.goods_id_arr
			  console.log('this.addmForm.goods_id_arr000',this.addmForm.goods_id_arr);	
			  let arr = row.goods_id_arr
			  
			  this.addmForm.goods_id = arr[ arr.length-1 ]
              this.addmForm.attribute = row.attribute
              this.addmForm.name = row.name
              this.addmForm.remarks = row.remarks
			  let id = row.id
			  console.log('1',this.addmForm.attribute);
			  axios.post('/admin/materialList/referweb',{id:id})
			  	.then(res =>{
			  	    this.addmForm.img_url = res.data.data.data.img_url
			  	}).catch(error =>{
			  	    console.log('请求失败：' + error);	
			  	})
			   
            } else {console.log('点开' );
			  this.outerVisible = true	
              this.title = '物资添加'
              this.addmForm.id = ''
              this.addmForm.goods_id = ''
			  this.addmForm.goods_id_arr = []
              this.addmForm.attribute = 1
              this.addmForm.name = ''
              this.addmForm.remarks = ''
			  this.addmForm.img_url = ''
            }
          },
          // 编辑、增加物资
          saveMaterial(formName) {
            this.$refs[formName].validate(valid => {
              if (valid) {

					  let arr = this.addmForm.goods_id_arr
					   console.log(this.addmForm.goods_id_arr,'shuzu',this.addmForm.goods_id_arr instanceof Array)
					  this.addmForm.goods_id = arr[ arr.length-1 ]
				   console.log( this.addmForm.goods_id,' this.addmForm.goods_id111')
                let  addmForm = this.addmForm
                console.log(addmForm)
                axios.post('/admin/materialList/refer',addmForm)
                  .then(res => {
                    if (res.data.code == 200) {
                        this.getdata()
                        this.$message({
                          message: '保存成功',
                          type: 'success'
                        });
                        this.$refs[formName].resetFields();
						this.$refs.upload.clearFiles();
                        this.outerVisible = false;	
						this.resetForm()
                    } else {
                        this.$message.info("保存失败！该名称已被使用")
                    }
                  })
                 
              } else {
                return false
              }
            })
          },
		  resetAddForm(formName){
			  this.$refs[formName].resetFields();
			  this.outerVisible = false
		  },
            // 编辑、增加物资分类
            saveGoods(formName) {
              this.$refs[formName].validate((valid) => {
                if (valid) {                     
                   let  addgForm = this.addgForm
                      console.log(addgForm)
                      axios.post('/admin/goods/goodsdo',addgForm)
                      .then(res => {
                      if (res.data.code == 200) {  
                        this.getgoodsdata()                        
                       this.$message({
                          message: '保存成功',
                          type: 'success'
                        });
                        this.$refs[formName].resetFields();
                        this.innerVisible = false
                      } else {
                        this.$message.info("保存失败！该名称已被使用")
                      }
                      })
                } else {
                  return false;
                }
              });
            },
          //导出文件
          downloadExcel() {
            let vm = this
            axios.post('/admin/materialList/exportone',{name:vm.formInline.name})
                .then((res) => {
                  let url = res.data.url
                  let file_name = res.data.file_name
                  let link = document.createElement("a");
                  link.style.display = "none";
                  link.href = url;
                  link.setAttribute = file_name;
                  document.body.appendChild(link);
                  link.click();
                  document.body.removeChild(link)
                })
                .catch((err) => {
                  console.log(err);
                });
            },
		  //上传单个图片
		  handleAvatarSuccess(res, file) {
				this.addmForm.img_url = res.data[0].url;
				 console.log('#',this.addmForm.img_url);
		  },
		  beforeAvatarUpload(file) {
			const isJPG = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg';
			const isLt2M = file.size / 1024 / 1024 < 2;
		  
			if (!isJPG) {
			  this.$message.error('上传头像图片只能是 JPG/PNG/JPEG 格式!');
			}
			if (!isLt2M) {
			  this.$message.error('上传头像图片大小不能超过 2MB!');
			}
			return isJPG && isLt2M;
		  },
		  postValueChange(value) {console.log(this.addmForm.goods_id_arr,'eeeeeeddd');
		  	if(this.$refs["postSelectRef"].getCheckedNodes()[0]){
		  		let pathlabel = this.$refs["postSelectRef"].getCheckedNodes()[0].uid
		  		this.CascaderLabel = pathlabel + 1
		  		console.log(this.CascaderLabel,'eeeeee');
		  	}			  
		  },

    },

  })

</script>
<style scoped>
  .el-table .el-table__cell:first-child{text-align: center;}
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 60px;
    height: 60px;
    line-height: 60px;
    text-align: center;
  }
  .avatar {
    width: 60px;
    height: 60px;
    display: block;
  }
    a{color:#409EFF;text-decoration: none;}
</style>
</body>
</html>